<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='search'>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='6' :md='12' :sm='24'>
            <a-form-item label='基地'>
              <a-select v-model='queryParams.sourceBase' placeholder='请选择基地' @change='sourceBaseChange'>
                <a-select-option v-for='(d,i) in sourceBaseList' :key='d.id' :value='d.id'>{{
                    d.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='6' :md='12' :sm='24'>
            <a-form-item label='地块'>
              <a-select v-model='queryParams.sourceGreenhouse' placeholder='请选择地块'>
                <a-select-option v-for='(d,i) in sourceGreenhouseList' :key='d.id' :value='d.id'>{{
                    d.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='6' :md='12' :sm='24'>
            <a-form-item label='冷库'>
              <a-select v-model:value='queryParams.storehouse' style='width: 100%;' placeholder='请选择冷库'>
                <a-select-option v-for='d in storehouseList' :key='d.id' :value='d.code'>{{ d.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <template v-if='toggleSearchStatus'>
            <a-col :xl='6' :lg='6' :md='12' :sm='24'>
              <a-form-item label='分拣日期'>
                <a-range-picker :style="{width: '100%'}" format='YYYY-MM-DD'
                                :placeholder="['开始时间', '结束时间']"

                                @change='onQueryDateChange' />
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='状态'>
                <!--                <a-input placeholder="请输入状态（-1待出库，0已出库，1删除 ）" v-model="queryParam.state"></a-input>-->
                <a-select v-model='queryParams.state' placeholder='请选择状态'>
                  <a-select-option v-for='(d,i) in stateList' :key='d.id' :value='d.id'>{{ d.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='入库方式'>
                <!--                <a-input placeholder="请输入状态（-1待出库，0已出库，1删除 ）" v-model="queryParam.state"></a-input>-->
                <a-select v-model='queryParams.inType' placeholder='请选择入库方式'>
                  <a-select-option v-for='(d,i) in intypeList' :key='d.id' :value='d.id'>{{ d.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl='6' :lg='6' :md='12' :sm='24'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='search' icon='search'>查询</a-button>
              <a-button type='primary' @click='resetSearch' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button @click='addModalShow' type='primary' icon='plus'>新增</a-button>
      <a-button type='primary' icon='download' :loading='exportLoading' @click="handleExportXlsALL('批量入库表主表')">导出
      </a-button>
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary" icon="import">导入</a-button>
            </a-upload>-->
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='flowerBatchDelete(selectedRowKeys)'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        class='j-table-force-nowrap'
        :columns='columns'
        :dataSource='flowerDataSource'
        :pagination='mainPagination'
        :loading='loading'
        :scroll='{ x: true }'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='mainPaginationChange'>

        <template slot='htmlSlot' slot-scope='text'>
          <div v-html='text'></div>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无图片</span>
          <img v-else :src='getImgView(text)' height='25px' alt=''
               style='max-width:80px;font-size: 12px;font-style: italic;' />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无文件</span>
          <a-button
            v-else
            :ghost='true'
            type='primary'
            icon='download'
            size='small'
            @click='uploadFile(text)'>
            下载
          </a-button>
        </template>

        <span slot='state' slot-scope='text, record'>
          <a-tag v-if='record.state==0'>草稿</a-tag>
          <a-tag class='ant-tag-green' v-else-if='record.state==1'>已入库</a-tag>
          <a-tag class='ant-tag-red' v-else-if='record.state==-2'>已删除</a-tag>
        </span>

        <span slot='action' slot-scope='text, record'>
          <a v-if='record.state==0' @click='editModalShow(record)'>编辑</a>
          <a-divider type='vertical' />
          <a v-if='record.state==1' style='color: red !important;' @click='exportInExcel(record)'>导出入库单</a>
          <a-divider type='vertical' />
          <a-button v-has="'tagin:sure'" v-if='record.state==0' type='primary' @click='editModalShow(record)'>
          确认入库
        </a-button>
        <a-button v-has="'tagin:sureBack'" v-if='record.state==1' type='' @click='editModalShow(record)'>
          撤销入库
        </a-button>

          <a-dropdown v-if='record.state==0'>
            <a class='ant-dropdown-link'>更多 <a-icon type='down' /></a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a-popconfirm title='确定删除吗?' @confirm='() => flowerDelete(record.state ,record.id)'>
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <!--    <tFlowerTagInMain2-modal ref="modalForm" @ok="modalFormOk"></tFlowerTagInMain2-modal>-->
    <a-modal v-model:visible='addOrEditVisible' width='80%' :title='firstModalTitle'
             :maskClosable='false'>
      <a-spin :spinning='firstModalSpinning' tip='数据保存中...'>
        <div>
          <a-row>
            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;width:80px;'>入库单号：</div>
              <div style='display: inline-block;width: 65%'>
                <input v-model='flower.no' disabled placeholder='自动生成' />
              </div>
            </a-col>

            <!--
                        <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                          <div style='display: inline-block;width:80px;'>账期：</div>
                          <div style='display: inline-block;width: 65%'>
                            <a-radio-group v-model='flower.ffrom' @change='periodChange'>
                              <a-radio v-for='(item,index) in periodList' :value='item'>{{ item }}</a-radio>
                            </a-radio-group>
                          </div>
                        </a-col>-->


            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;width:80px;'>来源：</div>
              <div style='display: inline-block;width: 65%'>
                <a-radio-group v-model='flower.ffrom' @change='ffromChange'>
                  <a-radio v-for='(item2,index) in ffromList' :value='item2'>{{ item2 }}</a-radio>
                </a-radio-group>
              </div>
            </a-col>

            <template v-if='flower.ffrom=="内部"'>
              <a-col :xl='8' :lg='8' :md='12' :sm='24' prop='sourceBase'>
                <div style='display: inline-block;color: red;'>*</div>
                <div style='display: inline-block;width:80px;'>基地：</div>
                <div style='display: inline-block;width: 65%'>
                  <a-select v-model='flower.sourceBase' pro='sourceBase' placeholder='请选择基地' style='width: 130px;'
                            @change='sourceBaseChange'>
                    <a-select-option v-for='(d,i) in sourceBaseList' :key='d.id' :value='d.id'>{{
                        d.name
                      }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-col>
              <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                <div style='display: inline-block;color: red;'>*</div>
                <div style='display: inline-block;width:80px;'>地块：</div>
                <div style='display: inline-block;width: inherit;'>
                  <a-select v-model='flower.sourceGreenhouse' placeholder='请选择地块' style='width: 100%;'>
                    <a-select-option v-for='(d,i) in sourceGreenhouseList' :key='d.id' :value='d.id'>{{
                        d.name
                      }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-col>
              <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                <div style='display: inline-block;color: red;'>*</div>
                <div style='display: inline-block;width:80px;'>批次：</div>
                <div style='display: inline-block;width: 65%'>
                  <j-dict-select-tag style='width: 100%' placeholder='请选择批次' :dict-code='productions'
                                     v-model='flower.productionId'></j-dict-select-tag>
                </div>
              </a-col>
            </template>
            <template v-if='flower.ffrom=="外部"'>
              <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                <div style='display: inline-block;color: red;'>*</div>
                <div style='display: inline-block;width:80px;'>经销商：</div>
                <div style='display: inline-block;width: 65%'>
                  <a-input style='width: 100%' placeholder='请输入经销商' v-model='flower.sealer'></a-input>
                </div>
              </a-col>
            </template>

            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;color: red;'>*</div>
              <div style='display: inline-block;width:80px;'>采摘人：</div>
              <div style='display: inline-block;width: 65%'>
                <a-input style='width: 100%' placeholder='请输入采摘/购人' v-model='flower.frompeople'></a-input>
              </div>
            </a-col>
            <!--            <a-col  :xl="8" :lg="8" :md="12" :sm="24">
                          <div style="display: inline-block;color: red;">*</div>
                          <div style="display: inline-block;width:80px;">产品：</div>
                          <div style="display: inline-block;width: 65%">
                            <j-dict-select-tag  v-model="flower.variety"  :triggerChange='true' dictCode='t_flower_variety_zz,name,id'
                                                placeholder='请输入产品'>
                            </j-dict-select-tag>
            &lt;!&ndash;                <input v-model="flower.variety" disabled placeholder="先选择批次" />&ndash;&gt;
                          </div>
                        </a-col>-->
            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;color: red;'>*</div>
              <div style='display: inline-block;width: 80px'>冷库：</div>
              <div style='display: inline-block;width: 65%'>
                <a-select v-model:value='flower.storehouse' style='width: 100%;' placeholder='请选择冷库'>
                  <a-select-option v-for='d in storehouseList' :key='d.id' :value='d.code'>{{ d.name }}
                  </a-select-option>
                </a-select>
              </div>
            </a-col>
            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;width: 80px'>分拣日期：</div>
              <div style='display: inline-block;width:65%'>
                <a-date-picker v-model:value='flower.sortTime'
                               :valueFormat='dateFormat'
                               :disabled-date='disabledDate'
                               disabled
                               placeholder='请选择分拣日期' />
              </div>
            </a-col>
          </a-row>
        </div>
        <a-divider />
        <div style='margin-top: -20px'>
          <span style='font-size: 20px;color: #0742f3;margin-bottom: 3px;margin-right: 30px;'>入库产品</span><span> <a-button
          type='primary' v-has="'tagin:add'" icon='plus' @click='varietyModalShow(flower)'>新增</a-button> </span>

          <div style='margin-top: 7px'>
            <a-table :columns='varietyColumns' :data-source='varietyDataSource'
                     bordered row-key='uuid'
                     :loading='varietyLoading'>

              <template v-for="tagNums in ['tagNum']" :slot='tagNums' slot-scope='text, record, index'>
                <div :key='tagNums' style='float: left;margin-right: 0'>
                  <input v-model:value='record.tagNum' placeholder='请输入入库数量' />
                </div>
              </template>

              <template slot='operation' slot-scope='text, record'>
                <a-popconfirm v-if='varietyDataSource.length' title='确定删除?'
                              @confirm='() => varietyDelete(record.uuid)'>
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </a-table>
          </div>
        </div>
      </a-spin>
      <template slot='footer'>
        <a-button key='back' :loading='firstModalSaveLoading' @click='addOrEditVisible=false'>
          关闭
        </a-button>

        <a-button v-has="'tagin:add'" v-if='flower.state==null || flower.state==""|| flower.state==0' type='primary'
                  :loading='firstModalSaveLoading' @click='flowerAddOrEdit'>
          保存
        </a-button>
        <a style='color:red!important;'> 如有修改，请先点【保存】，再点【确认入库】</a>
        <a-button v-has="'tagin:sure'" v-if='flower.state==0' type='primary' :loading='firstModalSaveLoading'
                  @click='sureDo(flower)'>
          确认入库
        </a-button>
        <a-button v-has="'tagin:sureBack'" v-if='flower.state==1' type='danger' :loading='firstModalSaveLoading'
                  @click='sureBackDo(flower)'>
          撤销入库
        </a-button>
      </template>
    </a-modal>
    <a-modal v-model:visible='varietyVisible' width='60%' title='产品选择' @ok='varietyAdd'>
      <div style='margin-bottom: 10px'>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block;width: 45px;'>产品：</div>
            <div style='display: inline-block;width: 70%'>
              <a-input v-model='queryVarietyParams.name' placeholder='请输入产品名称' allow-clear
                       @change='searchFlowerVarietys' />
            </div>
          </a-col>
          <a-col :span='10'>
            <div style='display: inline-block;width: 80px;'>商品编码：</div>
            <div style='display: inline-block;width: 70%'>
              <a-input v-model='queryVarietyParams.code' placeholder='请输入商品编码' allow-clear
                       @change='searchFlowerVarietys' />
            </div>
          </a-col>
          <a-col :span='4'>
            <a-button type='primary' icon='search' @click='searchFlowerVarietys'>
              查询
            </a-button>
          </a-col>
        </a-row>
      </div>
      <a-table :columns='selectVarietyColumns' :data-source='selectVarietyDataSource' bordered
               :loading='selectVarietyLoading'
               :row-selection="{selectedRowKeys: selectedRowKeys,type: 'checkbox',onChange:onVarietySelectChange,onSelect:varietyOnSelect,
               onSelectAll:varietyOnSelectAll}"
               row-key='uuid'
               :scroll='{y:280}'
               :pagination='varietyPagination'
               @change='varietyPaginationChange'
      ></a-table>
    </a-modal>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import TFlowerTagInMain2Modal from './modules/TFlowerTagInMain2Modal'
import JDate from '@/components/jeecg/JDate.vue'
import { downFile } from '@/api/manage'
import '@/assets/less/TableExpand.less'
import {
  getFlowerTagInMain2,
  getFlowerTagInMain2DetailByMainId,
  flowerTagInMain2Add,
  flowerTagInMain2Edit,
  flowerTagInMain2Delete,
  flowerTagInMain2DeleteBatch,
  getVarietyList,
  queryFlowerBase,
  queryGreenhouseByPd,
  getFlowerStorehouseDict,
  getFlowerCost,
  period, sureBack, sure
} from '../../api/vegetableAPI'

import { ifInteger, ifNumber } from '../../utils/ifNumber'
import { getCurrentYearAndMonth, getTodayDate } from '../../utils/getDate'
import { getUuid } from '../../utils/uuid'
import moment from 'moment'

export default {
  name: 'TFlowerTagInMain2List',
  mixins: [JeecgListMixin],
  components: {
    JDate,
    TFlowerTagInMain2Modal
  },
  data() {
    return {
      queryParams: {// 主页数据查询
        sourceBase: '',//基地
        sourceGreenhouse: '',//地块
        storehouse: '',//冷库
        sDate: '',//开始时间
        eDate: ''//结束时间
      },
      rangePikerDate: [],
      productions: 't_flower_production,code,code',
      queryVarietyParams: {// 商品选择弹窗的查询
        name: '',
        code: ''
      },
      stateList: [{ id: '', value: '全部' }, { id: 0, value: '草稿' }, { id: 1, value: '已入库' }, { id: 9, value: '已删除' }],//-1待出库，0已出库，1删除
      intypeList: [{ id: '', value: '全部' }, { id: '扫码入库', value: '扫码入库' }, { id: '手工入库', value: '手工入库' }],//-1待出库，0已出库，1删除

      description: '批量入库表主表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '状态',
          align: 'center',
          width: 70,
          dataIndex: 'state',
          scopedSlots: { customRender: 'state' }
        }, {
          title: '入库单号',
          align: 'center',
          width: 100,
          dataIndex: 'no'
        },
        {
          title: '账期',
          align: 'center',
          width: 100,
          dataIndex: 'period'
        }, {
          title: '基地',
          align: 'center',
          width: 120,
          dataIndex: 'sourceBase_dictText'
        },
        {
          title: '地块',
          align: 'center',
          width: 120,
          dataIndex: 'sourceGreenhouse_dictText'
        },
        {
          title: '成本中心',
          align: 'center',
          width: 120,
          dataIndex: 'cost_dictText'
        }, {
          title: '冷库',
          align: 'center',
          width: 120,
          dataIndex: 'storehouse_dictText'
        },
        {
          title: '分拣日期',
          align: 'center',
          width: 100,
          dataIndex: 'sortTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '入库方式',
          align: 'center',
          width: 90,
          dataIndex: 'inType'
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy_dictText'
        },
        {
          title: '创建日期',
          align: 'center',
          width: 120,
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 140,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/flower/tFlowerTagInMain2/list',
        delete: '/flower/tFlowerTagInMain2/delete',
        deleteBatch: '/flower/tFlowerTagInMain2/deleteBatch',
        exportXlsUrl: '/flower/tFlowerTagInMain2/exportXls',
        importExcelUrl: 'flower/tFlowerTagInMain2/importExcel'
      },
      dictOptions: {},
      flowerDataSource: [],
      firstModalTitle: '',
      firstModalSpinning: false,//第一个弹窗是否处于加载中
      addOrEditFlag: 'add',//打开的弹窗是新增还是编辑的标识
      varietyLoading: false,//是否显示第一个弹窗中表格的加载状态
      selectVarietyLoading: true,//是否显示第二个弹窗中表格的加载状态
      addOrEditVisible: false,//是否打开新增或编辑的弹窗
      varietyVisible: false,//是否打开商品选择的弹窗
      defaultSortTime: '',
      flower: {
        period: '',//账期
        sourceBase: '',//基地
        sourceGreenhouse: '',//地块
        storehouse: '',//冷库
        sortTime: ''//分拣日期
      },
      sourceBaseList: [],//基地列表
      sourceGreenhouseList: [],//地块列表
      storehouseList: [],//冷库列表
      costList: [],//成本中心列表
      dateFormat: 'YYYY-MM-DD',
      varietyColumns: [// 第一个弹窗的表头
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        }, {
          title: '采收产品',
          dataIndex: 'variety'
        }, {
          title: '商品编码',
          dataIndex: 'varietyCode'
        }, {
          title: '打包规格',
          dataIndex: 'packingSpecifications'
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength'
        }, {
          title: '等级',
          dataIndex: 'classes'
        }, {
          title: '入库数量',
          dataIndex: 'tagNum',
          scopedSlots: { customRender: 'tagNum' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 100,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      selectVarietyColumns: [// 第二个弹窗的表头
        {
          title: '产品',
          dataIndex: 'name'
        }, {
          title: '商品编码',
          dataIndex: 'code'
        }, {
          title: '规格',
          dataIndex: 'packingSpecifications'
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength'
        }, {
          title: '等级',
          dataIndex: 'classes'
        }
      ],
      varietyNumber: 1,
      varietyDataSource: [],// 第一个弹窗中的商品列表
      selectVarietyDataSource: [],// 第二个弹窗中可选择的商品列表
      selectVariety: [],// 第二个弹窗中已选择的商品
      mainPagination: {// 主页表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      varietyPagination: {// 商品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      firstModalSaveLoading: false,//第一个弹窗保存按钮是否处于加载中
      periodList: [],//从后台取回的账期列表
      ffromList: ['内部', '外部'],
      exportLoading: false
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  mounted() {
    this.queryFlowerTagInMain2()
    this.queryFlowerBase()
    // this.queryFlowerStorehouseDict()
    //this.queryCost()
  },
  created() {
    this.storehouseList = JSON.parse(localStorage.getItem('ch_storehouse') ? localStorage.getItem('ch_storehouse') : '')
    this.getPeriod()
  },
  methods: {
    moment,
    initDictConfig() {
    },
    search() {// 主页中根据条件查询
      this.mainPagination.current = 1
      this.queryFlowerTagInMain2()
    },
    onQueryDateChange(date, dateString) {// 日期段选择改变时的回调
      this.queryParams.sDate = dateString[0]
      this.queryParams.eDate = dateString[1]
    },
    resetSearch() {// 重置查询
      this.queryParams = {// 主页数据查询
        sourceBase: '',//基地
        sourceGreenhouse: '',//地块
        storehouse: '',//冷库
        sDate: '',//开始时间
        eDate: ''//结束时间
      }

      this.search()
    },
    // 日期选择框中不可选择的日期
    disabledDate(current) {
      return current < moment().subtract(1, 'day')//当前日期以前不可用
    },
    searchFlowerVarietys() {//根据条件查询商品选择弹窗中的商品列表
      this.varietyPagination.current = 1
      this.queryFlowerVarietys()
    },
    mainPaginationChange(pagination) {
      this.mainPagination.current = pagination.current
      this.mainPagination.pageSize = pagination.pageSize
      this.queryFlowerTagInMain2()
    },
    varietyPaginationChange(pagination) {
      this.varietyPagination = pagination
      this.queryFlowerVarietys()
    },
    addModalShow() {//打开第一个弹窗(新增)
      this.addOrEditFlag = 'add'
      this.firstModalTitle = '新增'
      this.flower = {
        id: '',
        period: this.periodList.length === 1 ? this.periodList[0] : this.periodList[1],//账期
        sourceBase: '',//基地
        sourceGreenhouse: '',//地块
        storehouse: '',//冷库
        sortTime: ''//分拣日期
      }
      this.varietyDataSource = []
      this.todayDate2()
      this.getPeriod()
      this.ffromList = ['内部', '外部']
      this.firstModalSpinning = false
      this.firstModalSaveLoading = false
      this.addOrEditVisible = !this.addOrEditVisible
    },
    editModalShow(record) {//打开第一个弹窗(编辑)
      this.addOrEditFlag = 'edit'
      this.firstModalTitle = '编辑'
      this.flower = record
      this.varietyDataSource.length = 0

      // this.sourceBaseChange(record.sourceBase)
      this.queryGreenhouseByPd(record.sourceBase)

      this.queryFlowerTagInMain2Detail(record.id)
      this.setPeriod()
      this.firstModalSpinning = false
      this.firstModalSaveLoading = false
      this.addOrEditVisible = !this.addOrEditVisible
    },
    varietyModalShow(flower) {//打开/关闭第二个弹窗
      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择商品而实际上没有选择任何商品的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0

      let varietyid = flower.variety
      /*      if(!varietyid){
           this.$message.error("请先选择产品")
           return
         }*/

      this.selectVariety = []
      this.varietyPagination = {// 商品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.queryVarietyParams = {// 商品选择弹窗的查询
        name: '',
        code: ''
      }
      if (varietyid) {
        this.queryVarietyParams.zzid = varietyid  //预留着   根据批次的id带着的产品id来查找产品。
      }
      this.queryFlowerVarietys()
      this.varietyVisible = !this.varietyVisible
    },
    queryFlowerTagInMain2() {//获取主页面中的订单列表
      this.loading = true
      this.flowerDataSource.length = 0
      let params = {
        pageNo: this.mainPagination.current,
        pageSize: this.mainPagination.pageSize
      }
      params = { ...this.queryParams, ...params }
      getFlowerTagInMain2(params).then(res => {
        if (res.success) {
          this.mainPagination.total = res.result.total
          this.flowerDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },
    todayDate2() {// 设置新增弹窗中的分拣日期的默认值为当前日期
      this.defaultSortTime = getTodayDate()
      this.flower.sortTime = getTodayDate()
    },
    queryFlowerBase() {//获取基地
      queryFlowerBase().then(res => {
        if (res.success) {
          this.sourceBaseList = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    queryGreenhouseByPd(baseId) {//获取地块
      if (baseId) {
        queryGreenhouseByPd(baseId).then(res => {
          if (res.success) {
            this.sourceGreenhouseList = res.result
          } else {
            this.$message.error('未找到对应的地块')
          }
        })
      }
    },
    queryFlowerStorehouseDict() {//获取冷库
      // getFlowerStorehouseDict().then(res=>{
      //   if (res.success) {
      //     this.storehouseList=res.result
      //   } else {
      //     this.$message.error(res.message)
      //   }
      // })
    },
    queryCost() {//获取成本中心
      getFlowerCost().then(res => {
        if (res.success) {
          this.costList = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    sourceBaseChange(e) {// 选择基地的Change
      this.queryGreenhouseByPd(e)
      this.productions = 't_flower_production,code,code,mainid=\'' + e + '\''

      this.flower.sourceGreenhouse = null
      delete this.flower.productionId
    },
    queryFlowerTagInMain2Detail(id) {//获取第一个弹窗的商品数据
      let params = {
        id: id
      }
      getFlowerTagInMain2DetailByMainId(params).then(res => {
        if (res.success) {
          this.varietyDataSource = res.result
          this.varietyDataSource.map(item => {
            item.uuid = getUuid()//为每个商品中添加uuid属性，作为table中的key
          })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    queryFlowerVarietys() {// 获取第二个弹窗中的商品列表
      this.selectVarietyLoading = true
      let params = {
        pageNo: this.varietyPagination.current,
        pageSize: this.varietyPagination.pageSize
      }
      params = { ...this.queryVarietyParams, ...params }

      getVarietyList(params).then(res => {
        if (res.success) {
          this.selectVarietyDataSource = res.result
          this.selectVarietyDataSource.map(item => {
            item.uuid = getUuid()//为每个商品中添加uuid属性，作为table中的key
            item.variety = item.name
            item.varietyCode = item.code
          })
          // 将varietyNumber封装进selectVarietyDataSource中的各用户对象中,为商品选择弹窗中table的key使用
          /*if (this.varietyPagination.current > 1) {
            this.varietyNumber = (this.varietyPagination.current - 1) * 10 + 1
          } else {
            this.varietyNumber = 1
          }
          for (let item of this.selectVarietyDataSource) {
            item.varietyNumber = this.varietyNumber
            this.varietyNumber += 1
          }*/
        } else {
          this.$message.error(res.message)
        }
        this.selectVarietyLoading = false
      })
    },
    onVarietySelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法单选
      this.selectionRows = selectionRows
    },
    varietyOnSelect(record, selected, selectedRows) {//选择/取消选择某个商品的回调
      if (selected) {//如果是选择某个商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety.push(record)
      } else {//如果是取消选择某个商品的操作，则从selectVariety中删除相应的商品
        this.selectVariety = this.selectVariety.filter(item => item.varietyNumber !== record.varietyNumber)
      }
    },
    varietyOnSelectAll(selected, selectedRows, changeRows) {//选择/取消选择所有商品的回调
      if (selected) {//如果是选择所有商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety = [...this.selectVariety, ...changeRows]
      } else {//如果是取消选择所有商品的操作，则从selectVariety中删除相应的商品
        for (let i of changeRows) {
          this.selectVariety = this.selectVariety.filter(item => item.varietyNumber !== i.varietyNumber)
        }
      }
    },
    varietyAdd() {// 第二个弹窗中的新增商品

      this.selectVariety.map(item => {
        item.id = ''
        item.createUser = ''
        item.createTime = ''
        item.updateUser = ''
        item.updateTime = ''
        item.number = ''
        item.totalprice = ''
      })
      for (let item of this.selectVariety) {
        this.varietyDataSource.push(item)
      }
      this.varietyVisible = !this.varietyVisible
    },
    varietyDelete(id) {// 第一个弹窗中删除商品
      const dataSource = [...this.varietyDataSource]
      this.varietyDataSource = dataSource.filter(item => item.uuid !== id)
    },
    flowerAddOrEdit() {// 确定新增或编辑入库单
      let allNumberFlag = true//是否所有的商品都有数量的标识

      if (this.flower.ffrom === '') {
        this.$message.error('请选择来源')
      } else if (this.flower.sourceBase === '' && this.flower.ffrom == '内部') {
        this.$message.error('请选择基地')
      } else if (!this.flower.sourceGreenhouse && this.flower.ffrom == '内部') {
        this.$message.error('请选择地块')
      } else if (!this.flower.productionId && this.flower.ffrom == '内部') {
        this.$message.error('请选择批次')
      } else if (!this.flower.sealer && this.flower.ffrom == '外部') {
        this.$message.error('请填写经销商')
      } else if (this.flower.frompeople === '') {
        this.$message.error('请选写采摘人')
      } else if (this.flower.variety === '') {
        this.$message.error('请选择产品')
      } else if (this.flower.storehouse === '') {
        this.$message.error('请选择冷库')
      } else if (this.flower.sortTime === '') {
        this.$message.error('请选择分拣日期')
      } else {
        if (this.varietyDataSource.length === 0) {
          this.$message.error('请至少添加一个产品')
          return
        }
        for (let item of this.varietyDataSource) {
          if (item.tagNum === '' || item.tagNum === null) {
            this.$message.error('请输入入库数量')
            allNumberFlag = false
            return
          }

          if (!ifInteger(item.tagNum)) {
            this.$message.error('入库数量必须为正整数')
            return
          }
        }
        if (allNumberFlag) {
          this.varietyDataSource.map(item => {//去掉每个商品对象中的uuid属性
            delete item.uuid
          })
          this.flower.tflowerTagIn2List = this.varietyDataSource// 将商品列表封装近flower中
          this.firstModalSpinning = true
          this.firstModalSaveLoading = true
          if (this.addOrEditFlag === 'add') {// 新增入库单的情况
            flowerTagInMain2Add(this.flower).then(res => {
              if (res.success) {
                this.queryFlowerTagInMain2()
                this.$message.success('新增入库成功')
                this.addOrEditVisible = false
              } else {
                this.$message.error(res.message)
              }
              this.firstModalSpinning = false
              this.firstModalSaveLoading = false
            })
          } else {
            flowerTagInMain2Edit(this.flower).then(res => {// 编辑入库单的情况
              if (res.success) {
                this.queryFlowerTagInMain2()
                this.$message.success('编辑入库成功')
                this.addOrEditVisible = false
              } else {
                this.$message.error(res.message)
              }
              this.firstModalSpinning = false
              this.firstModalSaveLoading = false
            })
          }
        }
        this.selectedRowKeys.length = 0//使新增或编辑后不显示批量删除的按钮
      }
    },
    flowerDelete(state, id) {
      if (state != 0) {
        this.$message.error('只有申请中的入库单才能删除！')
        return
      }
      flowerTagInMain2Delete({ id: id }).then(res => {
        if (res.success) {
          this.queryFlowerTagInMain2()
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    flowerBatchDelete(selectedRowKeys) {
      if (selectedRowKeys.length > 0) {
        let ids = ''
        for (let item of selectedRowKeys) {
          ids = ids + item + ','
        }
        flowerTagInMain2DeleteBatch({ ids: ids }).then(res => {
          if (res.success) {
            this.queryFlowerTagInMain2()
            this.selectedRowKeys.length = 0
            this.$message.success('批量删除成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    handleExportXlsALL(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      this.exportLoading = true
      let param = this.queryParams
      if (param.column == 'createTime') {
        // param.column=""
        // param.order=""
        delete param.column
        delete param.order
      }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
          this.exportLoading = false
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
          this.exportLoading = false
        }
      })
    },
    exportInExcel(record) {
      let dt = new Date()
      let fileName = '入库单' + record.no + '-' + dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()

      let urlss = '/flower/tFlowerTagInMain2/exportXlsForTemp'
      downFile(urlss, { id: record.id }).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    getPeriod() {
      period().then(res => {
        this.periodList = res
      })
    },
    //账期单选的change
    periodChange(e) {
      this.flower.period = e.target.value
    },
    ffromChange(e) {
      this.flower.ffrom = e.target.value
    },

    //设置账期（打开编辑弹窗时用）
    setPeriod() {
      period().then(res => {
        this.periodList = res
        if (this.periodList.length === 1) {//账期开关关闭时
          this.periodList.push(this.flower.period)
          this.periodList = Array.from(new Set(this.periodList))//去重
          this.periodList.sort()//升序排序
        }
      })
    },

    //审核
    sureDo(record) {
      this.firstModalSaveLoading = true
      this.firstModalSpinning = true
      let id = record.id
      let state = record.state
      if (!id || state != 0) {
        this.$message.warning('不符合审核条件！')
        return
      }
      sure({ 'id': id }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryFlowerTagInMain2()
          this.addOrEditVisible = !this.addOrEditVisible
        } else {
          this.$message.error(res.message)
        }
        this.firstModalSaveLoading = false
        this.firstModalSpinning = false
      })
    },

    //撤销审核
    sureBackDo(record) {
      this.firstModalSaveLoading = true
      this.firstModalSpinning = true
      let id = record.id
      let state = record.state
      if (!id || state != 1) {
        this.$message.error('不符合撤销审核条件！')
        return
      }
      if (record.inType == '扫码入库') {
        this.$confirm({
          title: '提示',
          content: '“扫码入库” 的入库单撤销将自动删除该入库单，是否确定？',
          loading: true,
          onOk: () => {
            sureBack({ 'id': id }).then(res => {
              if (res.success) {
                this.$message.success(res.message)
                this.queryFlowerTagInMain2()
                this.addOrEditVisible = !this.addOrEditVisible
              } else {
                this.$message.error(res.message)
              }
              this.firstModalSaveLoading = false
              this.firstModalSpinning = false
            })
          },
          onCancel: () => {
            this.firstModalSaveLoading = false
            this.firstModalSpinning = false
          }
        })
      } else {
        sureBack({ 'id': id }).then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.queryFlowerTagInMain2()
            this.addOrEditVisible = !this.addOrEditVisible
          } else {
            this.$message.error(res.message)
          }
          this.firstModalSaveLoading = false
          this.firstModalSpinning = false
        })
      }

    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.ant-col {
  margin-top: 10px;
  min-height: 40px;
}
</style>